package com.example.service.webhook.business.taobao.service;

import java.io.IOException;
import java.util.List;

import com.example.service.webhook.business.taobao.dto.*;
import com.example.service.webhook.business.taobao.entity.*;
import com.example.service.webhook.business.taobao.repository.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import com.example.service.webhook.business.email.entity.EmailBillShoppingSheetEntity;
import com.example.service.webhook.business.fund.dto.FundDetails;
import com.example.service.webhook.business.taobao.api.TaobaoClient;
import com.example.service.webhook.business.taobao.billitem.TaobaoTask;

/**
 * taobao处理类
 * userId+mappingId做为一个基础对象，mappingId是魔蝎为淘宝账号生成的一个id，一个淘宝账号的id不会变
 * ClassName: TaobaoService    
 * date: 2016年7月20日 下午5:35:35   
 * @author yuandong  
 * @version   
 * @since JDK 1.6
 */
@Service
public class TaobaoService {
	private static final Logger LOGGER = LoggerFactory.getLogger(TaobaoService.class);

	@Autowired
	private ThreadPoolTaskExecutor taskExecutor;
	@Autowired
	private TaobaoClient taobaoClient;
	@Autowired
	private UserInfoRepository userInfoRepository;
	@Autowired
	private TaobaoDeliverAddressRepository taobaoDeliverAddressRepository;
	@Autowired
	private RecentAddressRepository recentAddressRepository;
	@Autowired
	private TaobaoTradeInfoRepository taobaoTradeInfoRepository;
	@Autowired
	private TaobaoSuborderRepository taobaoSuborderRepository;

	@Autowired
	private TaobaoAlipayWealthRepository taobaoAlipayWealthRepository;


	/**
	 * 
	 * fetchBill:处理邮箱下面的所有账单 <br/>
	 * 在收到魔蝎的邮箱账单回调时执行<br/>
	 * for(保存账单){ 保存单条账单 －保存消费记录 －保存分期记录 }<br/>
	 * 
	 * @author yuandong
	 * @param task
	 * @since JDK 1.6
	 */
	public void fetchBill(final TaobaoTask task) {
		// 这里交给线程池处理，防止下面的业务处理时间太长，导致超时。
		// 超时会导致魔蝎数据进行重试，会收到重复的回调请求
		
		
		taskExecutor.execute(
				new Runnable() {
                    @Override
                    public void run() {
            			try {
            				//查询用户的基本信息
//            				saveUserInfo(task);
//            				//保存收货地址
//            				saveDeliverAddress(task);
//            				//保存最近订单的收货地址
//            				saveRecentAddress(task);
//            				//保存订单和商品
//            				saveTradeDetails(task);

							saveData(task);

            			} catch (Exception e) {
            				LOGGER.error("fetchBill failed. account:{}", task.getAccount(), e);
            			}
            		}
                }
				
				);
		
	}


	private void saveData(TaobaoTask task){
		try{
			TaobaoData taobaoData = taobaoClient.getData(task.getTaskId());
			if(taobaoData!=null){
				LOGGER.info("start deal taobao data......");
				//保存基本信息
				if(taobaoData.getUserinfo()!=null){
					TaobaoUserInfo taobaoUserInfo = taobaoData.getUserinfo();
					UserInfoEntity userInfoEntity = new UserInfoEntity();
					BeanUtils.copyProperties(taobaoUserInfo, userInfoEntity);
					userInfoEntity.setUserId(task.getUserId());
					UserInfoEntity oldUserInfo = userInfoRepository.getUserInfo(task.getUserId(),task.getMappingId());
					if(oldUserInfo==null){
						userInfoRepository.saveUserInfo(userInfoEntity);
					}else{
						userInfoEntity.setId(oldUserInfo.getId());
						userInfoEntity.setCreateTime(oldUserInfo.getCreateTime());
						userInfoRepository.updateUserInfo(userInfoEntity);
					}
				}

				//保存收货地址
				List<DeliverAddress> deliverAddressList = taobaoData.getDeliveraddress();
				if(deliverAddressList!=null&&!deliverAddressList.isEmpty()){
					taobaoDeliverAddressRepository.deleteDeliverAddress(task.getUserId(),task.getMappingId());
					for(DeliverAddress deliverAddress:deliverAddressList){
						DeliverAddressEntity basicEntity = new DeliverAddressEntity();
						BeanUtils.copyProperties(deliverAddress, basicEntity);
						basicEntity.setUserId(task.getUserId());
						taobaoDeliverAddressRepository.saveDeliverAddress(basicEntity);
					}
				}

				//保存最近交易记录的收货地址
				List<RecentDeliverAddress> recentDeliverAddressList = taobaoData.getRecentdeliveraddress();
				if(recentDeliverAddressList!=null&&!recentDeliverAddressList.isEmpty()){

					for(RecentDeliverAddress recentDeliverAddress:recentDeliverAddressList){
						RecentAddressEntity basicEntity = new RecentAddressEntity();
						BeanUtils.copyProperties(recentDeliverAddress, basicEntity);
						basicEntity.setUserId(task.getUserId());
						basicEntity.setMappingId(task.getMappingId());
						RecentAddressEntity isExist = recentAddressRepository.getRecentAddress(task.getUserId(), task.getMappingId(), recentDeliverAddress.getTradeId());
						if(isExist==null){
							recentAddressRepository.saveRecentAddress(basicEntity);
						}else{
							basicEntity.setId(isExist.getId());
							basicEntity.setCreateTime(isExist.getCreateTime());
							recentAddressRepository.updateRecentAddress(basicEntity);
						}
					}
				}

				//保存淘宝对应支付宝信息
				if(taobaoData.getTaobaoAlipayWealth()!=null){
					TaobaoAlipayWealth taobaoAlipayWealth = taobaoData.getTaobaoAlipayWealth();
					TaobaoAlipayWealthEntity taobaoAlipayWealthEntity = new TaobaoAlipayWealthEntity();
					BeanUtils.copyProperties(taobaoAlipayWealth, taobaoAlipayWealthEntity);
					taobaoAlipayWealthEntity.setUserId(task.getUserId());
					TaobaoAlipayWealthEntity isExistAw = taobaoAlipayWealthRepository.getAlipayWealth(task.getUserId(),task.getMappingId());
					if(isExistAw==null){
						taobaoAlipayWealthRepository.saveAlipayWealth(taobaoAlipayWealthEntity);
					}else{
						taobaoAlipayWealthEntity.setId(isExistAw.getId());
						taobaoAlipayWealthEntity.setCreateTime(isExistAw.getCreateTime());
						taobaoAlipayWealthRepository.updateAlipayWealth(taobaoAlipayWealthEntity);
					}
				}


				TradeDetailsRes tradeDetailsRes = taobaoData.getTradedetails();
				if (tradeDetailsRes != null && tradeDetailsRes.getSize() > 0) {
					List<TradeDetails> tradeDetailsList = tradeDetailsRes.getTradedetails();
					for (TradeDetails tradeDetails : tradeDetailsList) {
						TradeDetailEntity tradeDetailEntity = new TradeDetailEntity();
						BeanUtils.copyProperties(tradeDetails, tradeDetailEntity);
						tradeDetailEntity.setUserId(task.getUserId());

						//保存消费记录
						TradeDetailEntity isExist = taobaoTradeInfoRepository.getTradeDetailEntity(task.getUserId(), task.getMappingId(), tradeDetails.getTradeId());
						if(isExist==null){
							taobaoTradeInfoRepository.saveTradeDetail(tradeDetailEntity);
						}else{
							tradeDetailEntity.setId(isExist.getId());
							tradeDetailEntity.setCreateTime(isExist.getCreateTime());
							taobaoTradeInfoRepository.updateTradeDetail(tradeDetailEntity);
						}

						//保存商品信息
						List<TaobaoSubOrder> subOrders = tradeDetails.getSubOrders();
						if(subOrders!=null&&!subOrders.isEmpty()){
							taobaoSuborderRepository.deleteSubOrder(task.getUserId(), tradeDetails.getMappingId(), tradeDetails.getTradeId());
							for(TaobaoSubOrder taobaoSubOrder:subOrders){
								SubOrderEntity subOrderEntity = new SubOrderEntity();
								BeanUtils.copyProperties(taobaoSubOrder, subOrderEntity);
								subOrderEntity.setUserId(task.getUserId());
								taobaoSuborderRepository.saveSubOrder(subOrderEntity);
							}
						}

					}
				}
				LOGGER.info("end deal taobao data......");
			}


		}catch(Exception e){
			LOGGER.error("save taobao data error",e);
		}
	}
	
//	private void saveUserInfo(TaobaoTask task){
//		try{
//			UserInfoEntity userInfoEntity = loaduserInfoByCallApi(task.getUserId(),task.getTaskId());
//			UserInfoEntity oldUserInfo = userInfoRepository.getUserInfo(task.getUserId(),task.getMappingId());
//			if(oldUserInfo==null){
//				userInfoRepository.saveUserInfo(userInfoEntity);
//			}else{
//				userInfoEntity.setId(oldUserInfo.getId());
//				userInfoEntity.setCreateTime(oldUserInfo.getCreateTime());
//				userInfoRepository.updateUserInfo(userInfoEntity);
//			}
//		}catch(Exception e){
//			LOGGER.error("save taobao userinfo error",e);
//		}
//	}
//
//	private void saveDeliverAddress(TaobaoTask task){
//		try{
//			taobaoDeliverAddressRepository.deleteDeliverAddress(task.getUserId(),task.getMappingId());
//			loadDeliverAddressByCallApi(task.getUserId(),task.getTaskId());
//		}catch(Exception e){
//			LOGGER.error("saveDeliverAddress error",e);
//		}
//	}
//
//
//	private UserInfoEntity loaduserInfoByCallApi(String userId,String taskId) throws IOException {
//		TaobaoUserInfo taobaoUserInfo = taobaoClient.getUserInfo(taskId);
//		if(taobaoUserInfo!=null){
//			UserInfoEntity basicEntity = new UserInfoEntity();
//			BeanUtils.copyProperties(taobaoUserInfo, basicEntity);
//			basicEntity.setUserId(userId);
//			return basicEntity;
//		}
//		return null;
//	}
//
//
//	private void loadDeliverAddressByCallApi(String userId,String taskId) throws Exception {
//		List<DeliverAddress> deliverAddressList = taobaoClient.getDeliverAddress(taskId);
//		if(deliverAddressList!=null&&!deliverAddressList.isEmpty()){
//			for(DeliverAddress deliverAddress:deliverAddressList){
//				DeliverAddressEntity basicEntity = new DeliverAddressEntity();
//				BeanUtils.copyProperties(deliverAddress, basicEntity);
//				basicEntity.setUserId(userId);
//				taobaoDeliverAddressRepository.saveDeliverAddress(basicEntity);
//			}
//		}
//	}
//
//
//	private void saveRecentAddress(TaobaoTask task){
//		try{
//			List<RecentDeliverAddress> deliverAddressList = taobaoClient.getRecentAddress(task.getTaskId());
//			if(deliverAddressList!=null&&!deliverAddressList.isEmpty()){
//				for(RecentDeliverAddress recentDeliverAddress:deliverAddressList){
//					RecentAddressEntity basicEntity = new RecentAddressEntity();
//					BeanUtils.copyProperties(recentDeliverAddress, basicEntity);
//					basicEntity.setUserId(task.getUserId());
//					basicEntity.setMappingId(task.getMappingId());
//					RecentAddressEntity isExist = recentAddressRepository.getRecentAddress(task.getUserId(), task.getMappingId(), recentDeliverAddress.getTradeId());
//					if(isExist==null){
//						recentAddressRepository.saveRecentAddress(basicEntity);
//					}else{
//						basicEntity.setId(isExist.getId());
//						basicEntity.setCreateTime(isExist.getCreateTime());
//						recentAddressRepository.updateRecentAddress(basicEntity);
//					}
//				}
//			}
//		}catch(Exception e){
//			LOGGER.error("saveRecentAddress error",e);
//		}
//	}
//
//	private void saveTradeDetails(TaobaoTask task){
//		int page=1;
//		int pageSize=200;
//		try{
//
//			do {
//				TradeDetailsRes tradeDetailsRes = taobaoClient.getTradeDetailsRes(task.getTaskId(), page, pageSize);
//				if (tradeDetailsRes != null && tradeDetailsRes.getSize() > 0) {
//					pageSize = tradeDetailsRes.getSize();
//					List<TradeDetails> tradeDetailsList = tradeDetailsRes.getTradedetails();
//					for (TradeDetails tradeDetails : tradeDetailsList) {
//						TradeDetailEntity tradeDetailEntity = new TradeDetailEntity();
//						BeanUtils.copyProperties(tradeDetails, tradeDetailEntity);
//						tradeDetailEntity.setUserId(task.getUserId());
//
//						//保存消费记录
//						TradeDetailEntity isExist = taobaoTradeInfoRepository.getTradeDetailEntity(task.getUserId(), task.getMappingId(), tradeDetails.getTradeId());
//						if(isExist==null){
//							taobaoTradeInfoRepository.saveTradeDetail(tradeDetailEntity);
//						}else{
//							tradeDetailEntity.setId(isExist.getId());
//							tradeDetailEntity.setCreateTime(isExist.getCreateTime());
//							taobaoTradeInfoRepository.updateTradeDetail(tradeDetailEntity);
//						}
//
//						//保存商品信息
//						List<TaobaoSubOrder> subOrders = tradeDetails.getSubOrders();
//						if(subOrders!=null&&!subOrders.isEmpty()){
//							taobaoSuborderRepository.deleteSubOrder(task.getUserId(), tradeDetails.getMappingId(), tradeDetails.getTradeId());
//							for(TaobaoSubOrder taobaoSubOrder:subOrders){
//								SubOrderEntity subOrderEntity = new SubOrderEntity();
//								BeanUtils.copyProperties(taobaoSubOrder, subOrderEntity);
//								subOrderEntity.setUserId(task.getUserId());
//								taobaoSuborderRepository.saveSubOrder(subOrderEntity);
//							}
//						}
//
//					}
//				} else {
//					pageSize = 0;
//				}
//
//				page++;
//			} while (pageSize == 200);
//		}catch(Exception e){
//			LOGGER.error("saveTradeDetails error",e);
//		}
//	}
	

	
}
